package com.example.app1.util;

import android.content.SharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;

/**
 * 缓存操作工具类
 */
public class CacheUtil {
    public static void writeMsg(SharedPreferences sharedPreferences, boolean isSync, String msg) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(CacheKey.MSG.name(), msg);
        if (isSync) {
            edit.commit();
        } else {
            edit.apply();
        }
    }

    /**
     * 一次保存多个值
     * @param sharedPreferences 缓存工具对象
     * @param isSync 是否阻塞
     * @param keyAndValues key value键值对
     */
    public static void writeCache(SharedPreferences sharedPreferences, boolean isSync, String... keyAndValues) {
        SharedPreferences.Editor edit = sharedPreferences.edit();

        int i = 0;
        while (true) {
            if (i + 1 < keyAndValues.length) {
                edit.putString(keyAndValues[i], keyAndValues[i+1]);
            } else {
                break;
            }
            i += 2;
        }

        if (isSync) {
            edit.commit();
        } else {
            edit.apply();
        }
    }

    public static String[] getContents(SharedPreferences sharedPreferences) {
        String contentArrayJson = sharedPreferences.getString(CacheKey.CURRENT_CONTENT.name(), "");
        try {
            JSONArray array = new JSONArray(contentArrayJson);
            String[] contents = new String[array.length()];
            for (int i = 0; i < array.length(); i++) {
                contents[i] = array.getString(i);
            }
            return contents;
        } catch (JSONException ex) {
            return new String[]{};
        }
    }

    public static void writePlayAtIdx(SharedPreferences sharedPreferences, boolean isSync, int idx) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putInt(CacheKey.PLAY_AT_IDX.name(), idx);
        if (isSync) {
            edit.commit();
        } else {
            edit.apply();
        }
    }
}
